package com.app.service.impl.article;

import com.app.domain.po.article.ArticleTagPo;
import com.app.domain.vo.article.ArticleTagVo;
import com.app.framework.utils.CollectionUtils;
import com.app.framework.utils.StringsUtils;
import com.app.mapper.article.ArticleTagMapper;
import com.app.service.article.ArticleTagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 文章标签方法实现
 */
@Service
public class ArticleTagServiceImpl extends ServiceImpl<ArticleTagMapper, ArticleTagPo> implements ArticleTagService {

    /**
     * 标签修改、添加
     *
     * @param tagIds    标签ID集合
     * @param articleId 文章ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTags(List<Long> tagIds, Long articleId) {
        baseMapper.deleteTags(articleId);
        if (CollectionUtils.isNoNull(tagIds)) {
            List<ArticleTagPo> articleTagPos = new ArrayList<>();
            for (Long tagId : tagIds) {
                ArticleTagPo articleTagPo = new ArticleTagPo();
                articleTagPo.setArticleId(articleId);
                articleTagPo.setCreateTime(new Date());
                articleTagPo.setUpdateTime(new Date());
                articleTagPo.setTagId(tagId);
                articleTagPos.add(articleTagPo);
            }
            saveBatch(articleTagPos);
        }
    }

    /**
     * 根据文章ID查询标签集合
     *
     * @param articleId 文章ID
     */
    @Override
    public List<ArticleTagVo> selectArticleTags(Long articleId) {
        return baseMapper.selectArticleTags(articleId);
    }

    /**
     * 根据标签ID集合批量查询文章ID集合
     *
     * @param tagIds 标签ID集合
     */
    @Override
    public List<Long> selectArticleIdsByTagIds(List<Long> tagIds) {
        //ID集合去重
        List<Long> uniqueTagIds = StringsUtils.deduplication(tagIds);
        return baseMapper.selectArticleIdsByTagIds(uniqueTagIds);
    }

}